<?php
/**
 * 公共函数库
 * @package WordPress
 * @subpackage wheatv
 */

/*根据父级分类ID获取子分类ID*/
function wheatv_get_category_root_id($cat)   {   
	$this_category = get_category($cat); 
	while($this_category->category_parent)  {   
	 $this_category = get_category($this_category->category_parent);  
	 }   
	 return $this_category->term_id; 
}

/*获取文章别名*/
function wheatv_post_slug() {
	$post_data = get_post($post->ID, ARRAY_A);
	$slug = $post_data['post_name'];
	return $slug; 
}

/*根据分类ID获取分类别名*/
function wheatv_get_cat_slug($cate_name){
	$cat_ID = get_cat_ID($cate_name); 
	$thisCat = get_category($cat_ID);
	$cat_slug = $thisCat->slug;
	return $cat_slug;
}

/*根据分类ID获取分类名称*/
function wheatv_get_cat_name($cat_ID){
	$thisCat = get_category($cat_ID);
	$cat_name = $thisCat->name;
	return $cat_name;
}

/*获取文章第一篇图片作为缩略图*/
function catch_that_image($para) {
    global $post, $posts;
    $first_img = '';
    ob_start();
    ob_end_clean();
    $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
    $first_img = $matches [1] [0];
    if(empty($first_img)){ //Defines a default image
      $site_url = bloginfo('template_url');
      $first_img = $site_url."/images/no.jpg";
    }
	if($para=='img'){
      return $first_img;
	}elseif($para=='counts'){
	  return $output;
	}
}

/*自动截取字符串*/
function wheatv_excerpt($title_str,$max_length) {
	if (mb_strlen($title_str,'utf-8') > $max_length ) {
	  $title_str = mb_substr($title_str,0,$max_length,'utf-8').'…';
	}
return $title_str;
}

/*根据页面ID获取页面别名*/
function get_page_slug($page_id){
	$post_data = get_post($page_id, ARRAY_A);
    $slug = $post_data['post_name'];
    return $slug; 
}

/*根据页面ID获取页面标题*/
function get_page_title($page_id){
	$post_data = get_post($page_id, ARRAY_A);
    $title = $post_data['post_title'];
    return $title; 
}

/*翻页函数*/
if ( !function_exists('wheatv_pagenavi') ) {
    function wheatv_pagenavi( $p = 5 ) { 
        if ( is_singular() ) return; 
        global $wp_query, $paged;
        $max_page = $wp_query->max_num_pages;
        if ( $max_page == 1 ) return; 
        if ( empty( $paged ) ) $paged = 1;
        //echo '<span class="wheatv_pages">Page: ' . $paged . ' of ' . $max_page . ' </span> '; 
        if ( $paged > 1 ) p_link( $paged - 1, '上一页', '«' );
        if ( $paged > $p + 1 ) p_link( 1, '最前页' );
        if ( $paged > $p + 2 ) echo '<em>...</em>';
        for( $i = $paged - $p; $i <= $paged + $p; $i++ ) { 
            if ( $i > 0 && $i <= $max_page ) $i == $paged ? print "<span class='wb-numbers curPage'>{$i}</span> " : p_link( $i );
        }
        if ( $paged < $max_page - $p - 1 ) echo '<em>...</em>';
        if ( $paged < $max_page - $p ) p_link( $max_page, '最后页' );
        if ( $paged < $max_page ) p_link( $paged + 1,'下一页', '»' );
    }
    function p_link( $i, $title = '', $linktype = '' ) {
        if ( $title == '' ) $title = "第 {$i} 页";
        if ( $linktype == '' ) { $linktext = $i; } else { $linktext = $linktype; }
        echo "<a class='wb-numbers' href='", esc_html( get_pagenum_link( $i ) ), "' title='{$title}'>{$linktext}</a> ";
    }
}

/*图片广告调用*/
function wheatv_ad($var,$width,$height){
	$ad = get_option($var);
	$ad = trim(strip_tags($ad));
	$ad_arr = explode(',',$ad); 
	echo '<a href="'.$ad_arr[1].'" target="_blank"><img src="'.$ad_arr[0].'" alt="'.$ad_arr[2].'" border="0" style="width:'.$width.'px;height:'.$height.'px" /></a>';
}

/*自定义Rewrite规则*/
function add_custom_post_rewrite_rules($rules) {
  $custom_rules = array(
    '([0-9]{4})/([0-9]{1,2})/([^/]+)-([0-9]+)\.html$' => 'index.php?year=$matches[1]&monthnum=$matches[2]&name=$matches[3]&page=$matches[4]',
  );
  $rules = array_merge($custom_rules, $rules);
 
  return $rules;
}
add_filter('post_rewrite_rules', 'add_custom_post_rewrite_rules');
 
/*自定义文章URL*/
function my_wp_link_pages($args = '') {
  $args .= ($args ? '&' : '') . 'echo=0';
  $links = wp_link_pages($args);
  $links = preg_replace_callback('|([0-9]{4}/[0-9]{1,2}/)([^/]+)(\.html)(/)([0-9]+)|', 'custom_page_link', $links);
  echo $links;
}
function custom_page_link($matches) {
  return $matches[1].$matches[2].'-'.$matches[5].$matches[3];
}

/*格式化文章输出*/
function wheatv_format($content) {
	$new_content = '';
	$pattern_full = '{(\[raw\].*?\[/raw\])}is';
	$pattern_contents = '{\[raw\](.*?)\[/raw\]}is';
	$pieces = preg_split($pattern_full, $content, -1, PREG_SPLIT_DELIM_CAPTURE);
	foreach ($pieces as $piece) {
		if (preg_match($pattern_contents, $piece, $matches)) {
			$new_content .= $matches[1];
		} else {
			$new_content .= wptexturize(wpautop($piece));
		}
	}
	return $new_content;
}
remove_filter('the_content', 'wpautop');
remove_filter('the_content', 'wptexturize');
add_filter('the_content', 'wheatv_format', 99);
add_filter('widget_text', 'wheatv_format', 99);
add_filter('widget_text', 'do_shortcode');


/*输出文章列表
$cat_id - 分类ID
$items - 输出数量
$echo - True:直接输出 False:返回值
*/
function wheatv_posts_list($cat_id = '', $items = 5, $echo = TRUE){
	$return_html = '';
	$posts = get_posts('numberposts='.$items.'&order=DESC&orderby=date&category='.$cat_id);
	$count_post = count($posts);
    if(!empty($posts)){
	  foreach($posts as $post){
	    $return_html.= '<li>';
		$return_html.= '<a href="'.get_permalink($post->ID).'" title="'.$post->post_title.'">'.$post->post_title.'</a>';
		$return_html.= '</li>';
	  }
	}
	if($echo)
	{
		echo $return_html;
	}
	else
	{
		return $return_html;
	}
}

/*面包屑导航*/
function wheatv_breadcrumbs() {
  $delimiter = '&raquo;';
  $name = '首页'; //text for the 'Home' link
  $currentBefore = '<span class="current">';
  $currentAfter = '</span>';
  if ( !is_home() && !is_front_page() || is_paged() ) {
    echo '<div class="nowPosition">';
    global $post;
    $home = get_bloginfo('url');
    echo '<a href="' . $home . '">' . $name . '</a> ' . $delimiter . ' ';
    if ( is_category() ) {
      global $wp_query;
      $cat_obj = $wp_query->get_queried_object();
      $thisCat = $cat_obj->term_id;
      $thisCat = get_category($thisCat);
      $parentCat = get_category($thisCat->parent);
      if ($thisCat->parent != 0) echo(get_category_parents($parentCat, TRUE, ' ' . $delimiter . ' '));
      echo $currentBefore;
      single_cat_title();
      echo $currentAfter;
    } elseif ( is_day() ) {
      echo '<a href="' . get_year_link(get_the_time('Y')) . '">' . get_the_time('Y') . '</a> ' . $delimiter . ' ';
      echo '<a href="' . get_month_link(get_the_time('Y'),get_the_time('m')) . '">' . get_the_time('F') . '</a> ' . $delimiter . ' ';
      echo $currentBefore . get_the_time('d') . $currentAfter;
    } elseif ( is_month() ) {
      echo '<a href="' . get_year_link(get_the_time('Y')) . '">' . get_the_time('Y') . '</a> ' . $delimiter . ' ';
      echo $currentBefore . get_the_time('F') . $currentAfter;
    } elseif ( is_year() ) {
      echo $currentBefore . get_the_time('Y') . $currentAfter;
    } elseif ( is_single() && !is_attachment() ) {
      $cat = get_the_category(); $cat = $cat[0];
      echo get_category_parents($cat, TRUE, ' ' . $delimiter . ' ');
      echo $currentBefore;
      the_title();
      echo $currentAfter;
    } elseif ( is_attachment() ) {
      $parent = get_post($post->post_parent);
      $cat = get_the_category($parent->ID); $cat = $cat[0];
      echo get_category_parents($cat, TRUE, ' ' . $delimiter . ' ');
      echo '<a href="' . get_permalink($parent) . '">' . $parent->post_title . '</a> ' . $delimiter . ' ';
      echo $currentBefore;
      the_title();
      echo $currentAfter;
    } elseif ( is_page() && !$post->post_parent ) {
      echo $currentBefore;
      the_title();
      echo $currentAfter;
    } elseif ( is_page() && $post->post_parent ) {
      $parent_id  = $post->post_parent;
      $breadcrumbs = array();
      while ($parent_id) {
        $page = get_page($parent_id);
        $breadcrumbs[] = '<a href="' . get_permalink($page->ID) . '">' . get_the_title($page->ID) . '</a>';
        $parent_id  = $page->post_parent;
      }
      $breadcrumbs = array_reverse($breadcrumbs);
      foreach ($breadcrumbs as $crumb) echo $crumb . ' ' . $delimiter . ' ';
      echo $currentBefore;
      the_title();
      echo $currentAfter;
    } elseif ( is_search() ) {
      echo $currentBefore . '搜索结果&#39;' . get_search_query() . '&#39;' . $currentAfter;
    } elseif ( is_tag() ) {
      echo $currentBefore . 'Posts tagged &#39;';
      single_tag_title();
      echo '&#39;' . $currentAfter;
    } elseif ( is_author() ) {
       global $author;
      $userdata = get_userdata($author);
      echo $currentBefore . 'Articles posted by ' . $userdata->display_name . $currentAfter;
    } elseif ( is_404() ) {
      echo $currentBefore . 'Error 404' . $currentAfter;
    }
    if ( get_query_var('paged') ) {
      if ( is_category() || is_day() || is_month() || is_year() || is_search() || is_tag() || is_author() ) echo ' (';
      echo __('Page') . ' ' . get_query_var('paged');
      if ( is_category() || is_day() || is_month() || is_year() || is_search() || is_tag() || is_author() ) echo ')';
    }
    echo '</div>';
  }
}
?>